/******************************************************************************************************
Author:Accenture IDC
Bhumika Udani               v1.0            dt 10 February 2011
Bhumika Udani               v1.1            dt 19 February 2011      Secondary owner notes share added
Sapna Jaamdar               v1.2            dt 08 April 2011         Re-factored and bulkified
Bhumika Udani 				v1.3          	Test Demo     
******************************************************************************************************/
public class customSharingClass{
     
    /**Method to share a Lead notes if the lead was previously owned by sharkpool and MC accpets it*/  
    public static void NotesOwnerId(map<id,id> QueueLeadsMapID){    
        List <Notes__share> queueNoteShareList = new List<Notes__share>();                             
        List <Notes__c> notesInLeads = new List<Notes__c>();
        List <Id> notesIds = new List<id>();
        List <Notes__share> deleteAlreadySharedNotesList = new List<Notes__share>();
        List <Group> SfaPublicGroup = new List<Group>();
            
        SfaPublicGroup= [select id from Group where name = 'SFA NJ Queue Group' or name = 'SFA SLC Queue Group' ];      
        //Collect all the notes contained in Lead
        for(Notes__c N :[select id,lead__r.ownerid, Lead__c, ownerid from Notes__c where Lead__c in: QueueLeadsMapID.keyset()])
        {
            notesInLeads.add(N);
            notesIds.add(N.Id);         
        }
        deleteAlreadySharedNotesList = [select id,userOrGroupId,parentid from Notes__share where userOrGroupId in : SfaPublicGroup and parentid in :notesIds];               
         for(Notes__c nt : notesInLeads){                                 
            //check if Notes onwer is not the Lead owner, if true share the notes record
            if(nt.ownerid != QueueLeadsMapID.get(nt.Lead__c)){            
                try{                  
                   //Create a new Notes__Share record to be inserted in to the Notes_Share table.  
                   Notes__Share queueNoteShareObj = new Notes__Share();               
                   //Populate the queueNoteShare record with the ID of the Lead owner for sharing. 
                   queueNoteShareObj.ParentId = nt.id;
                   queueNoteShareObj.UserOrGroupId = QueueLeadsMapID.get(nt.Lead__c);            
                   queueNoteShareObj.AccessLevel = 'Read';                          
                   //queueNoteShareObj.RowCause = Schema.Notes__Share.RowCause.Queue_Lead_Notes_Access__c;                    
                   //Add the new Share record to the list of new Share records.     
                   queueNoteShareList.add(queueNoteShareObj);  
                  }
              catch(exception ex){    
                  System.debug('I have an exception : '+ex);} 
             }                   
          }   
        //Delete the already shared records     
         if(deleteAlreadySharedNotesList != null && deleteAlreadySharedNotesList.size()>0){            
                Database.DeleteResult[] deletednotesResult =Database.delete(deleteAlreadySharedNotesList,false);  
                system.debug('Deleted Records are '+deletednotesResult);
          }
         // Insert all of the newly created Share records and capture save result                                           
         if(queueNoteShareList != null && queueNoteShareList.size() > 0){            
                Database.SaveResult[] notesShareInsertResult = Database.insert(queueNoteShareList,false);
                system.debug('Insert notes Share result '+notesShareInsertResult);
         }                  
    } 
/**************************************************************************************************************/     
     /** For the Leads moving into the queue, Lead notes should be shared to the Queue owners **/
    public static void LeadsNotesintoQueue(map<id,id> leadsIntoQueueMapID){    
    
    ListViewIds__c LVI = ListViewIds__c.getInstance();     
    Id SfaNJQueueId  = LVI.SFA_OOR_New_Jersey_Sharkpool__c;            
    Id SfaSLCQueueId = LVI.SFA_OOR_Salt_Lake_Sharkpool__c;    
    //Collect the NJ and SLC Public Group id
    group SfaNJPublicGroup = [select id from Group where name = 'SFA NJ Queue Group'];
    group SfaSLCPublicGroup = [select id from Group where name = 'SFA SLC Queue Group'];
    List <Notes__share> notesInQueueShareList = new List<Notes__share>();                             
    List <Notes__share> deleteQueueNotes = new List<Notes__share>();
    List <Notes__c> notesLeads = new List<Notes__c>();
    List <id> notesid = new List<id>();

    //Collect all the notes contained in Lead
    for(Notes__C N :[select id,lead__r.ownerid, Lead__c, ownerid from Notes__c where Lead__c in: leadsIntoQueueMapID.keyset()])
    {
        notesLeads.add(N);
        notesid.add(N.id);
    }
    //Delete the already shared records     
    deleteQueueNotes = [select id,userOrGroupId,parentid from Notes__share where parentid in : notesid];
    
    if(deleteQueueNotes != null && deleteQueueNotes.size() > 0){           
        Database.deleteResult[] deleteQueueNotesResult = Database.delete(deleteQueueNotes,false);
        system.debug('Delete Notes into Queue '+deleteQueueNotesResult);
     }    
    
    for(notes__c qnt:notesLeads){                     
        // Share the notes record with entire Public group based on the office 
           try{ 
                  
                Notes__Share queueNoteShareObj = new Notes__Share();
                queueNoteShareObj.ParentId = qnt.id;
                queueNoteShareObj.AccessLevel = 'Read';
                //Share with NJ public group if ownerid is NJ Queue
                    if(leadsIntoQueueMapID.get(qnt.Lead__c) == SfaNJQueueId ){
                         queueNoteShareObj.UserOrGroupId = SfaNJPublicGroup.id;
                     } 
                    
                    //Share with SLC public group if ownerid is SLC Queue
                    else if(leadsIntoQueueMapID.get(qnt.Lead__c)== SfaSLCQueueId){
                        queueNoteShareObj.UserOrGroupId = SfaSLCPublicGroup.id;
                    }
                notesInQueueShareList.add(queueNoteShareObj);                               
                }catch(exception exce) {
                    //system.debug('Lead notes into Queue exception' +exce);          
                            }
                }
        
              // Insert all of the newly created Share records and capture save result    
              if(notesInQueueShareList != null && notesInQueueShareList.size() > 0){
                 
               Database.SaveResult[] leadnotesShareInsertResult = Database.insert(notesInQueueShareList,false);
               //system.debug('Lead Notes moving into Queue Insert result ' +leadnotesShareInsertResult);
              } 
    } //ending the LeadsNotesintoQueue method
    
public static void accountNotesShare(map<id,account> accountMap){
        List <Notes__share> accountNoteShareList = new List<Notes__share>();                             
        List <Notes__share> deleteAccountSharedNotesList = new List<Notes__share>();
        List <Notes__c> notesInAccount = new List<Notes__c>();
        List <Id> notesIds = new List<Id>();

        //Collect all the notes contained in Lead
        for(Notes__c N : [select id,Account__r.ownerid,Opportunity__c, Account__c, ownerid from Notes__c where Account__c in: accountMap.keyset()]){
            notesInAccount.add(N);
            notesIds.add(N.id);
        }

        deleteAccountSharedNotesList = [select id,userOrGroupId,parentid from Notes__share where parentid in : notesInAccount ];     
        
     for(Notes__c accNote : notesInAccount){
            system.debug('DDDDDDDD');
             try{
             // Create a new Notes__Share record to be inserted in to the Notes_Share table.  
             Notes__Share accountNoteShareObj = new Notes__Share();
             
             accountNoteShareObj.ParentId = accNote.id;
             accountNoteShareObj.AccessLevel = 'Read';
             accountNoteShareObj.UserOrGroupId = accNote.account__r.ownerid;
        
             system.debug('OBOB '+accNote.account__r.ownerid);        
             
             accountNoteShareList.add(accountNoteShareObj);
             system.debug('Account Note in Share list'+accountNoteShareList);
               }catch(exception accex){
               system.debug('Account notes exception '+accex);
                 }
            } 
     //Delete the previously shared Account Notes               
     if(deleteAccountSharedNotesList!= null && deleteAccountSharedNotesList.size() > 0){   
         
               Database.deleteResult[] deleteAccountNotesResult = Database.delete(deleteAccountSharedNotesList,false);
               system.debug('Deleted Account Notes '+deleteAccountNotesResult);
         }
         
     if(accountNoteShareList != null && accountNoteShareList.size() > 0){   
      
              // Insert all of the newly created Share records and capture save result    
       
           Database.SaveResult[] accountnotesShareInsertResult = Database.insert(accountNoteShareList,false);
           system.debug('Account Notes Insert result ' +accountnotesShareInsertResult);
              }             
    }    
public static void leadSecondaryOwnerNotesShare(map<id,id> secondaryOwnerIds,map<id,Lead> leadOldMap){

        List <Notes__share> sowner_leadNoteShareList = new List<Notes__share>();                             
        List <Notes__c> notesInLeads = new List<Notes__c>();
        List <Notes__share> deleteSOwnerSharedNotesList = new List<Notes__share>();
        List<id> sOwnerid = new List<id>();

       //Collect all the notes contained in Lead
        notesInLeads = [select id,Lead__r.ownerid, Lead__r.Secondary_Owner__c, ownerid from Notes__c where Lead__c in: secondaryOwnerIds.keyset()];
                          
     for(Notes__c lNote : notesInLeads){             
             sOwnerid.add(leadOldMap.get(lNote.Lead__c).Secondary_Owner__c);
                         
             try{
             // Create a new Notes__Share record to be inserted in to the Notes_Share table.  
             Notes__Share leadNoteShareObj = new Notes__Share();
             
             leadNoteShareObj.ParentId = lNote.id;
             leadNoteShareObj.AccessLevel = 'Read';
             leadNoteShareObj.UserOrGroupId = secondaryOwnerIds.get(lNote.Lead__c);                    
             sowner_leadNoteShareList.add(leadNoteShareObj);
               }catch(exception lex){
               system.debug('Secondary Owner Lead notes exception '+ lex);
                 }
            } 
     
        deleteSOwnerSharedNotesList = [select id,userOrGroupId,parentid from Notes__share where parentid in : notesInLeads and UserOrGroupId in:sOwnerid ];             
     
     //Delete the previously shared Lead secondary Owner Notes               
         if(deleteSOwnerSharedNotesList != null && deleteSOwnerSharedNotesList.size() > 0){
         
               Database.deleteResult[] deleteSOnwerNotesResult = Database.delete(deleteSOwnerSharedNotesList,false);
               system.debug('Deleted shared secondary owner lead notes '+deleteSOnwerNotesResult);
             }
                             
         if(sowner_leadNoteShareList!= null && sowner_leadNoteShareList.size() > 0){   
      
              // Insert all of the newly created Share records and capture save result       
           Database.SaveResult[] sowner_NotesShareInsertResult = Database.insert(sowner_leadNoteShareList,false);
           system.debug('Secondary owner lead notes insert result ' +sowner_NotesShareInsertResult);
              }              
  } 
}